$(function(){

	/* 佣金计划搜索 */
	$('#cmii-search-btn').click(function(){
		
		//初始化清空记录
		$("#cmii-list").html('');
		var CmiiSelect = $("#cmii-select").val();//选择的模式
		
		//获取用户身份
		if(_tb_token_==""){
			$.ajax({
				url: "http://pub.alimama.com/common/getUnionPubContextInfo.json" ,
				success: function(data){
					_tb_token_ = data.data._tb_token_;
				}
			});
		}
		
		//获取店铺
		var ShopName = $("#cmii-search").val();//店铺名称
		var ShopArr = [];//切割数据
		if(ShopName.indexOf(",")>=0){//逗点分割
			ShopArr = ShopName.split(',');
			if(ShopArr.length<=0){
				alert("结果为空");	
				return;
			}
		}else{
			ShopName = ShopName.replace("所属店铺",'');
			ShopArrTemp = ShopName.split('\n');
			ShopArrKey = [];
			for(v in ShopArrTemp){
				if(ShopArrTemp[v] != "" && $.inArray(ShopArrTemp[v],ShopArr)){
					ShopArr.push(ShopArrTemp[v]);
				}
			}
		}
		for(v in ShopArr){
			val = ShopArr[v];
			$.ajax({
				url: "http://pub.alimama.com/shopsearch/shopList.json?q="+val ,
				success: function(data){
					if(data.data.pagelist[0].oriMemberId != undefined){
						
						var shopName    = data.data.pagelist[0].extNick;//店铺名称
						var oriMemberId = data.data.pagelist[0].oriMemberId;
						
						//获取店铺计划
						$.ajax({
							url: "http://pub.alimama.com/shopdetail/campaigns.json?oriMemberId="+oriMemberId ,
							success: function(data){
								
								var campaignList = data.data.campaignList;
								var exsitApplyList = data.data.exsitApplyList;
								var EALArr = [];
								var top1 = "";//寻找最高
								
								/* 整理有状态的数据 */
								for(v in exsitApplyList){
									var Arr = [];
										Arr['status'] = exsitApplyList[v]['status'];
									EALArr[exsitApplyList[v]['campaignId']] = Arr;
								}
								
								for(v in campaignList){
									if(top1==''){
										top1 = campaignList[v];	
									}else{
										if(campaignList[v].avgCommission > top1.avgCommission){
											top1 = campaignList[v];
										}
									}
								}
								campaignId = top1['campaignId'];
								if(CmiiSelect == 0 || campaignId > 0){//选择下拉判断
								
									/* 制作数据 */
									cmiiMakeTable(shopName,top1,EALArr);
								
								}
							}
						});		
					}
				}
			});
		}
	});
	
});

/* init */
var _tb_token_ = "";

/* 
*	制作表格
*   status 1（待审核） 2(通过) 3（拒绝）
*/
var cmiiStatus = [];
	cmiiStatus[1] = '<font class="cmii-status-1">待审核</font>';
	cmiiStatus[2] = '<font class="cmii-status-2">通过</font>';
	cmiiStatus[3] = '<font class="cmii-status-3">拒绝</font>';
function cmiiMakeTable(shopName,data,EALArr){
	
	var html = "";
	 	html += '<tr>';
        html += '<td>';
		if(data['campaignId']!=0){//判断是否通用计划
			html += '  <input type="checkbox" />';
		}
		html += '</td>';
		html += '<td>'+data['campaignId']+'</td>';
        html += '<td>'+shopName+'</td>';
        html += '<td class="am-hide-sm-only">'+data['campaignName']+'('+data['avgCommissionToString']+')';
		if(EALArr[data['campaignId']]!= undefined){
			html += "["+cmiiStatus[EALArr[data['campaignId']]['status']]+"]";	
		}
        html += '</td><td>';
		if(data['campaignId']!=0 && EALArr[data['campaignId']] == undefined){//判断是否通用计划
			html += '<div class="am-btn-toolbar">';
			html += '<div class="am-btn-group am-btn-group-xs">';
			html += '<button class="am-btn am-btn-default am-btn-xs am-text-secondary Apply-btn" data-campId="'+data['campaignId']+'" data-shopKeeperId="'+data['shopKeeperId']+'"  id="'+data['campaignId']+'-'+data['shopKeeperId']+'"><span class="am-icon-pencil-square-o"></span> 执行计划</button>';
		}
        html += '</div>';
        html += '</div>';
        html += '</td>';
        html += '</tr>';
		
		$("#cmii-list").append(html);
		
		/* 监听按钮事件 */
		$("#"+data['campaignId']+'-'+data['shopKeeperId']).click(function(){	
			Apply(this);
		});
		
		$('#iframepage', window.parent.document).attr('height',$(document).height());
}

/* 申请计划 */
function Apply(obj){
	var applyVal = $("#cmii-apply").val();
	$.ajax({
		type: 'POST',
		data: { campId: $(obj).attr('data-campId'), keeperid : $(obj).attr('data-shopKeeperId'), applyreason: applyVal , _tb_token_ : _tb_token_ },
		url: "http://pub.alimama.com/pubauc/applyForCommonCampaign.json" ,
		success: function(data){
			if(data.ok == true){
				alert("执行成功,请刷新页面");
				$(obj).hide();	
			}else{
				alert("执行失败");
			}	
		}
	});	
}